package lol_stream_manager;

import com.sun.org.apache.regexp.internal.REUtil;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class RTMP_Dumper {
    public boolean isOnline;
    public int streamType = -1; // 0: twitch | 1: owned
    
    public String channel;
    public String stream_name;
    public String swfPlayer;
    public String play;
    public String token;
    public String connect;
    
    public String rtmpDumpCMD;
    
    public long flvSize = 0;
    
        // Twitch
    public RTMP_Dumper( String channel ) throws DocumentException, MalformedURLException, IOException {
        this.channel = channel;
        
        URL metaURL = new URL( "http://www.justin.tv/meta/" + channel + ".xml?on_site=true" );
        SAXReader metaReader = new SAXReader();
        Document metaDocument = metaReader.read( metaURL );
        this.stream_name = metaDocument.selectSingleNode( "//meta//stream_name" ).getText();
        Node nPlayerHTML = metaDocument.selectSingleNode( "//meta/playerHTML" );
        this.swfPlayer = Utility.matchRegex( nPlayerHTML.getText(), "swfobject.embedSWF\\(\"([^\"]+)\"");
        
//        List<Node> lBitrate = metaDocument.selectNodes( "//meta/restricted_bitrate_types" );
        
        URL usherURL = new URL( "http://usher.justin.tv/find/" + stream_name + ".xml" );
        SAXReader usherReader = new SAXReader();
        Document usherDocument = usherReader.read( usherURL );
        Node nPlay = usherDocument.selectSingleNode( "//nodes//live/play" );
        if( nPlay != null){
            isOnline = true;
            this.play = nPlay.getText();
            this.token = usherDocument.selectSingleNode( "//nodes//live/token" ).getText();
            this.connect = usherDocument.selectSingleNode( "//nodes//live/connect" ).getText();

            this.rtmpDumpCMD = 
                    "C:\\Users\\Mystic\\Downloads\\rtmpdump-2.3-windows\\rtmpdump.exe"
                    + " -r \"" + connect + "/" + play + "\""
                    + " -j \"" + token.replace("\"", "\\\"") + "\""
                    + " --swfVfy \"" + swfPlayer + "\""
                    + " --stop " + Utility.rtmpDumpMaxSec
                    + " -v -o " + channel + ".flv";

    //        this.rtmpDumpCMD = 
    //                "C:\\Users\\Mystic\\Downloads\\rtmpdump-2.3-windows\\rtmpdump.exe"
    //                + " -r \"" + connect + "\""
    //                + " -a \"app\""
    //                + " -f \"WIN 11,0,1,152\""
    //                + " -W \"" + swfPlayer + "\""
    //                + " -p \"" + "http://www.twitch.tv/" + channel + "\""
    //                + " -j \"" + token.replace("\"", "\\\"") + "\""
    //                + " --live -y \"" + play + "\""
    //                + " -o " + channel + ".flv";

            //(new CMDThread(channel, rtmpDumpCMD, 5000)).start();
            
            execRtmpDump();
        } else
            isOnline = false;
    }

    
    // own3d.tv
    public RTMP_Dumper( String channel, String id ) throws DocumentException, MalformedURLException, IOException {
        this.channel = channel;
        
        URL onlineURL = new URL( "http://api.own3d.tv/liveCheck.php?live_id=" + id );
        SAXReader onlineReader = new SAXReader();
        Document onlineDocument = onlineReader.read( onlineURL );
        this.isOnline = Boolean.parseBoolean( onlineDocument.selectSingleNode( "//own3dReply/liveEvent/isLive" ).getText() );
        
        if(!this.isOnline)
            return;

        URL cfgURL = new URL( "http://www.own3d.tv/livecfg/" + id + "?autoplay=true" );
        SAXReader cfgReader = new SAXReader();
        Document cfgDocument = cfgReader.read( cfgURL );
        Node c = cfgDocument.selectSingleNode("//config/channels/channel");
        this.stream_name = ((Element) c).attributeValue("nameLink");
        
        List<Node> channels = cfgDocument.selectNodes( "//config/channels/channel/clip/item" );
        this.connect = null;
        Node con = null;
        for(Node n : channels)
            if(n instanceof Element){
                String tmp = ((Element)n).attribute("base").getValue();
                if( tmp.startsWith("rtmp")){
                    this.connect = tmp;
                    con = n;
                }
            }
        if( this.connect == null ){
            System.out.println("For the stream: " + channel + ", there is no valid channel.");
            this.isOnline = false;
            return;
        }
        
        Node stream = con.selectSingleNode("stream");
        this.play = ((Element) stream).attributeValue("name");
        
        this.rtmpDumpCMD = 
                "C:\\Users\\Mystic\\Downloads\\rtmpdump-2.3-windows\\rtmpdump.exe"
                + " -r \"" + connect + "\""
                + " -p \"" + stream_name + "\""
                + " -W \"" + "http://static.llnw.own3d.tv/player/Own3dPlayerV3_11.swf" + "\""
                + " --live -y \"" + play + "\""
                + " --stop " + Utility.rtmpDumpMaxSec
                + " -o " + channel + ".flv";

        execRtmpDump();
    }
    
    public void execRtmpDump() throws IOException {
        File f = new File(channel + ".flv");
        if( f.exists() )
            f.delete();
//        
        Utility.chronometer ch = new Utility.chronometer();
//        Runtime rt = Runtime.getRuntime();
//        Process p = rt.exec( rtmpDumpCMD );
//        while( ch.getChrono() < Utility.rtmpDumpTimeout
//            && f.length() < Utility.rtmpDumpMaxSize ){}

        execcmd.ExecCMD.exec( rtmpDumpCMD, Utility.rtmpDumpTimeout, new File(channel + "_rtmpdump.txt"));
        System.out.println(channel + " stream dumped: " + f.length() + " bytes in " + ch);
//        p.destroy();
        
        this.flvSize = f.length();
    }

}
